package com.liujit.common.domain.result;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.liujit.common.utils.DozerConvertor;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 分页返回结果
 * @Author LiuJun
 * @Date 2020/8/12 4:24 下午
 */
@Data
@NoArgsConstructor
@ApiModel(value = "PageBean", description = "分页返回结果")
@JsonPropertyOrder({ "pageNumber", "pageSize", "total", "pages", "size", "rows" })
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class PageBean<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "总记录数")
    private Long total;

    @ApiModelProperty(value = "总页数")
    private Long pages;

    @ApiModelProperty(value = "第几页")
    private Long pageNumber;

    @ApiModelProperty(value = "每页记录数")
    private Long pageSize;

    @ApiModelProperty(value = "结果集")
    private List<T> rows;

    @ApiModelProperty(value = "当前页的数量<=pageSize")
    private Integer size;

    public static <S, T> PageBean page(IPage<S> page, Class<T> cls) {
        PageBean<T> pageBean = new PageBean<>();
        pageBean.setTotal(page.getTotal());
        pageBean.setPages(page.getPages());
        pageBean.setPageNumber(page.getCurrent());
        pageBean.setPageSize(page.getSize());
        List<S> records = page.getRecords();
        if (records == null) {
            pageBean.setRows(new ArrayList());
        } else {
            pageBean.setRows(DozerConvertor.convertor(records, cls));
        }
        pageBean.setSize(pageBean.getRows().size());
        return pageBean;
    }

    public static <T> PageBean page(IPage<T> page) {
        PageBean<T> pageBean = new PageBean<>();
        pageBean.setTotal(page.getTotal());
        pageBean.setPages(page.getPages());
        pageBean.setPageNumber(page.getCurrent());
        pageBean.setPageSize(page.getSize());
        List<T> records = page.getRecords();
        if (records == null) {
            pageBean.setRows(new ArrayList());
        } else {
            pageBean.setRows(records);
        }
        pageBean.setSize(pageBean.getRows().size());
        return pageBean;
    }
}
